package com.novabluetooth.views;

import java.util.ArrayList;
import java.util.List;

import com.health.NovaApplication;
import com.health.R;
import com.health.tablebean.BTDevice;
import com.health.tools.GlobalConts;
import com.health.tools.SPUtil;
import com.nova.BaseActivity;
import com.novabluetooth.adapter.BlueToothDeviceAdapter;
import com.novabluetooth.services.BluetoothConstant;

import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 蓝牙设备绑定
 * 
 * @author nova
 *
 */
public class BluetoothDeviceBindActivity2 extends BaseActivity
		implements OnItemClickListener, OnItemLongClickListener, android.view.View.OnClickListener {
	/* 取得默认的蓝牙适配器 */
	private BluetoothAdapter _bluetooth = BluetoothAdapter.getDefaultAdapter();
	/* 用来存储搜索到的蓝牙设备 */
	private List<BluetoothDevice> _devices = new ArrayList<BluetoothDevice>();
	/* 是否完成搜索 */
	private List<BTDevice> scanList = new ArrayList<BTDevice>();
	private List<BTDevice> savedList = new ArrayList<BTDevice>();
	com.health.db.FDbManager fdbmanger = NovaApplication.fdbmanger;
	private ListView saveListView;
	private ListView scanListView;
	private BlueToothDeviceAdapter savedAdapter;
	private BlueToothDeviceAdapter scanAdapter;
	private Button fanhui;
	private Button save;
	BluetoothAdapter mBluetoothAdapter;// ble
	BluetoothManager mBluetoothManager;
	// private BluetoothAdapter mBluetoothAdapter2;// 蓝牙2.0
	private static final long SCAN_PERIOD = 60000;
	RadioGroup ew_group;
	RadioButton ew_button2;
	RadioButton ew_button4;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.bluetooth_sbcl_bind_discovery);
		saveListView = (ListView) findViewById(R.id.bluetooth_saved_lv);
		scanListView = (ListView) findViewById(R.id.bluetooth_scan_lv);
		fanhui = (Button) findViewById(R.id.btn_back);
		fanhui.setOnClickListener(this);
		save = (Button) findViewById(R.id.btn_up);
		ew_group = (RadioGroup) findViewById(R.id.ew_group);
		ew_button2 = (RadioButton) findViewById(R.id.ew_button2);
		ew_button4 = (RadioButton) findViewById(R.id.ew_button4);
		if (SPUtil.getisBlooth2(BluetoothDeviceBindActivity2.this, false)) {
			ew_button2.setChecked(true);
			ew_button4.setChecked(false);
		} else {
			ew_button2.setChecked(false);
			ew_button4.setChecked(true);
		}

		View scanHead = View.inflate(this, R.layout.bluetooth_sbcl_bind_head, null);
		View saveHead = View.inflate(this, R.layout.bluetooth_sbcl_bind_head, null);
		setHeadTitle("已经绑定的设备", saveHead);
		setHeadTitle("搜索到的设备", scanHead);
		saveListView.addHeaderView(saveHead);
		scanListView.addHeaderView(scanHead);
		scanListView.setOnItemClickListener(this);
		saveListView.setOnItemClickListener(this);
		saveListView.setOnItemLongClickListener(this);
		showList();

		initBlooth();

		scanLeDevice(true);
	}

	private void setHeadTitle(String title, View head) {
		TextView tv = (TextView) head.findViewById(R.id.bluetooth_head_tv);
		tv.setText(title);
	}

	@Override
	protected void onDestroy() {

		Log.w("TAG", "onDestroy");
		scanLeDevice(false);
		boolean isBlooth2;
		// RadioButton checkEd=(RadioButton)
		// findViewById(ew_group.getCheckedRadioButtonId());
		// if("耳温枪蓝牙2.0".equals(checkEd.getText().toString())){
		// isBlooth2=true;
		// }else{
		// isBlooth2=false;
		// }
		if (ew_button2.isChecked()) {
			isBlooth2 = true;
		} else {
			isBlooth2 = false;
		}
		// Editor edit = NovaApplication.MyPreferences.edit();
		// SharedPreferences MyPreferences =
		// getSharedPreferences(GlobalConts.SHAREPREFRENCE_NAME,
		// Activity.MODE_PRIVATE);
		// Editor edit = MyPreferences.edit();
		// edit.putBoolean("isBlooth2", isBlooth2);
		// edit.commit();
		SPUtil.setisBlooth2(BluetoothDeviceBindActivity2.this, isBlooth2);
		super.onDestroy();
	}

	private void showList() {
		savedList = new ArrayList<>();
		savedList = fdbmanger.findAllBT(BTDevice.class);
		savedAdapter = new BlueToothDeviceAdapter(this, savedList);
		saveListView.setAdapter(savedAdapter);

		scanList = new ArrayList<>();
		scanAdapter = new BlueToothDeviceAdapter(this, scanList);
		scanListView.setAdapter(scanAdapter);

	}

	/* 显示列表 */
	protected void showScanDevices() {
		scanList = new ArrayList<>();
		for (int i = 0, size = _devices.size(); i < size; ++i) {
			BluetoothDevice d = _devices.get(i);
			BTDevice device = new BTDevice();
			Log.i("nova", d.getName());
			String novaName = BluetoothConstant.getNovaDevice(d.getName());
			if (TextUtils.isEmpty(novaName)) {
				return;
			}
			device.setName(novaName);
			device.setMacAddress(d.getAddress());
			if (!scanList.contains(device)) {

				Log.e("TAG", device.getName() + "#####");
				scanList.add(device);

			}
		}
		scanAdapter = new BlueToothDeviceAdapter(this, scanList);
		scanListView.setAdapter(scanAdapter);
		scanAdapter.notifyDataSetChanged();
		scanLeDevice(true);
	}

	private boolean isSavedDevice(BTDevice device, List<BTDevice> list) {
		boolean isSaved = false;
		if (list.size() < 0) {
			return isSaved;
		}
		for (BTDevice btDevice : list) {
			if (btDevice.equals(device)) {
				isSaved = true;
				break;
			}
		}
		return isSaved;
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		if (position == 0) {
			return;
		}
		if (parent.equals(saveListView)) {
			BTDevice savedDevice = savedList.get(position - 1);
		} else if (parent.equals(scanListView)) {
			getNewSavedList();
			BTDevice device = scanList.get(position - 1);
			if (!isSavedDevice(device, savedList)) {
				fdbmanger.saveBT(device);
				savedList.add(device);
				savedAdapter.setInfoList(savedList);
				savedAdapter.notifyDataSetChanged();
				Toast.makeText(this, "已绑定设备：" + device.getName(), 0).show();
			} else {
				Toast.makeText(this, "设备已存在", 0).show();
			}
		}

	}

	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
		if (position != 0) {
			new AlertDialog.Builder(this).setTitle("确认删除").setMessage("确定删除所选项吗？")
					.setPositiveButton("删除", new OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							getNewSavedList();
							BTDevice btDevice = savedList.get(position - 1);
							fdbmanger.deleteBT(btDevice);
							savedList.remove(btDevice);
							savedAdapter.setInfoList(savedList);
							savedAdapter.notifyDataSetChanged();

						}
					}).setNegativeButton("取消", null).show();
		}
		return true;
	}

	private void getNewSavedList() {
		savedList = fdbmanger.findAllBT(BTDevice.class);
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		if (id == R.id.btn_back) {
			finish();
		} else {
		}

	}

	/**
	 * 初始化蓝牙信息
	 * 
	 * @author 王婷婷
	 * @date 2015年12月18日 上午10:41:48
	 */
	private void initBlooth() {
		System.out.println("00000000000000000");
		if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
			Log.w("noticeservice-----------111----", "手机不支持BLE");
		}

		mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
		mBluetoothAdapter = mBluetoothManager.getAdapter();
		// mBluetoothAdapter2 = BluetoothAdapter.getDefaultAdapter();

		// Checks if Bluetooth is supported on the device.
		if (mBluetoothAdapter == null) {
			Log.w("noticeservice-----------222----", "手机不支持蓝牙");
		}
		Log.w("noticeservice-----------tt----", "手机支持蓝牙");
		// 开启蓝牙
		if (!mBluetoothAdapter.isEnabled()) {
			boolean flag = mBluetoothAdapter.enable();
			// 开启蓝牙成功还是失败
			if (flag) {
				NovaApplication.isBluetoothOpen = true;
			} else {
				NovaApplication.isBluetoothOpen = false;
			}

		} else {
			NovaApplication.isBluetoothOpen = true;
		}

	}

	public void scanLeDevice(final boolean enable) {
		if (enable) {
			System.out.println("开始检测 ");
			Log.w("开始检测", "正在搜索检测设备");
			mBluetoothAdapter.startLeScan(mLeScanCallback);
		} else {
			Log.w("扫描失败", "扫描设备失败");
			mBluetoothAdapter.stopLeScan(mLeScanCallback);
		}
	}

	// Device scan callback.
	private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {

		@Override
		public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
			try {
				if (device.getName() != null) {
					Log.e("TAG", device.getName());
					Log.w("TAG", "device.getName():" + device.getName());
					// 不是设备列表中的数据继续扫描
					String novaName = BluetoothConstant.getNovaDevice(device.getName());
					if (TextUtils.isEmpty(novaName)) {
						return;
					}
					/* 将结果添加到列表中 */
					if (!scanList.contains(device)) {
						/* 显示列表 */
						Log.w("TAG", device.getName() + "*****************");
						_devices.add(device);
						scanLeDevice(false);
						runOnUiThread(new Runnable() {
							public void run() {
								showScanDevices();
							}
						});
					} else {
						scanLeDevice(true);
					}

				}
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
	};

	// 捕获返回键的方法1
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			// 按下BACK，同时没有重复
			finish();
		}

		return super.onKeyDown(keyCode, event);
	}

}
